<?php

namespace App\Api\Controllers;

use App\Api\Validate\MiniUserValidate;
use App\Api\Validate\ReviewValidate;
use App\Models\Review;
use Illuminate\Http\Request;

class ReviewController extends BaseController
{
    public function add(Request $request)
    {
        $params = $request->all();

        (new ReviewValidate())->add($params);

        $checkInId = $this->checkReview();
        if (!is_int($checkInId)) {
            return $this->fail(404, $checkInId);
        }

        $params['openid'] = $this->user->openid;
        $params['room_check_in_id'] = $checkInId;
        $result = Review::add($params);
        if ($result) {
            return $this->success(200,'感谢您的评价~');
        }
        return Failed(50000,  ["File" => __CLASS__, "Action" => __FUNCTION__, "Line" => __LINE__, 'message' => $result]);
    }


    public function check()
    {
        $result = $this->checkReview();
        if (is_int($result)) {
            return $this->success();
        }
        return $this->fail(404, $result);
    }


    protected function checkReview()
    {
        // 判断是否在入住期间
        $living = (new MiniUserValidate())->checkLiving($this->user->openid);

        // 获取入住次数
        $count = (new Review())->getCountByUser($this->user->id, $living->id);
        if ($count > 2) {
            return '单笔订单最多评论3次';
        }

        return $living->id;
    }

    public function list(Request $request)
    {
        $pageNum  = $request->get("page_num");
        $pageSize = $request->get("page_size",20);
        $columns = ['id', 'room_check_in_id', 'review', 'images', 'service_rating', 'health_rating', 'facilities_rating', 'network_rating', 'created_at'];
        $model = Review::where(['user_id' => $this->user->id])
            ->orderBy("id", "desc")
            ->paginate($pageSize, $columns, "page", $pageNum);
        $list = $model->getCollection();
        foreach ($list as &$item) {
            $item->images = json_decode($item->images, true);
        }
        return Success(10100, [
            "data" => $list,
            "page_info" => [
                'current' => $model->currentPage(), 'page_size' => (int)$pageSize, "count" => $model->total(),
                "pages"   => $model->lastPage()
            ]
        ]);
    }
}
